using System.Collections;
using Klak.Motion;
using UnityEngine;

// 直升机事件回调
public class HelicopterEvent : MonoBehaviour
{
    private BrownianMotion _brownianMotion;
    private Coroutine _motionCoroutine;

    void Start()
    {
        _brownianMotion = GetComponent<BrownianMotion>();

        //默认不进行布朗运动
        _brownianMotion.positionFrequency = 0;
        _brownianMotion.rotationFrequency = 0;
    }

    public void TakeOff()
    {
        Debug.Log("起飞");
        StartMotion();
    }

    public void Land()
    {
        Debug.Log("降落");
        StopMotion();
    }

    #region 布朗运动
    /// <summary>
    /// 开始布朗运动的方法
    /// </summary>
    void StartMotion()
    {
        if (_motionCoroutine != null) StopCoroutine(_motionCoroutine);

        _motionCoroutine = StartCoroutine(LerpMotion(0, 0.2f, 3f));
    }

    /// <summary>
    /// 停止布朗运动的方法
    /// </summary>
    void StopMotion()
    {
        if (_motionCoroutine != null) StopCoroutine(_motionCoroutine);

        _motionCoroutine = StartCoroutine(LerpMotion(_brownianMotion.positionFrequency, 0f, 1f));
    }

    /// <summary>
    /// 布朗运动插值协程
    /// 实现布朗运动的平滑过渡效果
    /// </summary>
    /// <param name="start">起始值</param>
    /// <param name="end">目标值</param>
    /// <param name="duration">过渡时间（秒）</param>
    IEnumerator LerpMotion(float start, float end, float duration)
    {
        float elapsed = 0f;// 已过去的时间

        // 循环直到达到指定持续时间
        while (elapsed < duration)
        {
            // 设置位置和旋转频率为当前渐变值
            _brownianMotion.positionFrequency = Mathf.Lerp(start, end, elapsed / duration);
            _brownianMotion.rotationFrequency = Mathf.Lerp(start, end, elapsed / duration);

            // 累加帧时间（使用Time.deltaTime保证帧率无关）
            elapsed += Time.deltaTime;

            yield return null;
        }

        // 确保最终精确达到目标值（避免浮点数精度问题）
        _brownianMotion.positionFrequency = end;
        _brownianMotion.rotationFrequency = end;
    }
    #endregion
}
